package com.ihrm.company.service;

import com.ihrm.common.service.BaseService;
import com.ihrm.common.util.IdWorker;
import com.ihrm.company.dao.DepartmentDao;
import com.ihrm.domain.company.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.swing.text.html.HTMLDocument;
import java.util.List;
import java.util.Optional;

@Service
public class DepartmentService extends BaseService{

    @Autowired
    private DepartmentDao departmentDao;

    @Autowired
    private IdWorker idWorker;

    /**
     * 1,保存部门
     */
    public void add(Department department){
        String id = idWorker.nextId()+"";
        department.setId(id);
        departmentDao.save(department);
    }

    /**
     * 2，更新部门
     */
    public void update(Department department){
        Department department1 = departmentDao.findById(department.getId()).get();
        department1.setCode(department.getCode());
        department1.setIntroduce(department.getIntroduce());
        department1.setName(department.getName());
        departmentDao.save(department);
    }

    /**
     * 3，根据id查询部门
     */
    public Department findById(String id){
        return departmentDao.findById(id).get();
    }

    /**
     * 4，查询全部部门列表
     */
    public List<Department> findAll(String companyId){

        /**
         * 用户构造查询条件
         */
       /* Specification<Department> spec = new Specification<Department>() {
            @Override
            public Predicate toPredicate(Root<Department> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                return cb.equal(root.get("companyId").as(String.class),companyId);
            }
        };*/
        return departmentDao.findAll(getSpec(companyId));
    }

    /**
     * 5，根据id删除部门
     */
    public void deleteById(String id){
        departmentDao.deleteById(id);
    }
}
